$(function () {
    var productInfo = {};
    var selectPriceId = "";
    // 申购规则
    let buyRule = "";

    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg); //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    let buySetData = null;
    let useSetData = null;
    // 购买和使用的数量
    let buyNum = 0;
    let useNum = 0;
    // 产品id
    let productId = getUrlParam("productId");
    // 产品最后的价格
    let customerProductPrice = 0;
    // 安全相关价格
    let safetyPrice =0.00;

    /**
     * @description:函数描述 获取数据产品详情
     * @return 返回值
     * @param productId {Number} 产品id
     */

    function getDataInfo(productId) {
        $.ajax({
            timeout: 30000,
            url: window.Http + "/customer/product/info",
            type: "GET",
            headers: {
                Authorization: "Bearer " + sessionStorage.getItem("Token"),
            },
            data: {productId: getUrlParam("productId")},
            success: function (res) {
                if (res.code === 200) {
                    // console.log('JSON.parse(buyRule)', JSON.parse(buyRule))
                    // console.log('buyRule', buyRule)
                    let status = {
                        "-1": "保存",
                        0: "正常",
                        1: "故障",
                        2: "未审核",
                        3: "未测试",
                    };
                    let buyStatus = {
                        "-1": "申购状态",
                        0: "可用次数",
                        2: "可用记录数",
                        3: "可用字节数",
                        4: "可用时间",
                    };
                    let buyType = {
                        "-1": "未申购",
                        0: res.data.canUseNumber,
                        2: res.data.canUseRecords,
                        3: res.data.canUseBytes,
                        4: res.data.canUseTime,
                    };
                    // 产品类型
                    let productType = {
                        1: "在线产品",
                        2: "套餐产品",
                        4: "离线产品",
                    };
                    productInfo = res.data;
                    $("#dataTitle").text(res.data.productName);
                    $("#createTime").text(res.data.createTime.slice(0, 10));
                    $("#status").text(status[`${res.data.status}`]);
                    $("#buyCount").html(res.data.buyCount);
                    $("#visitCount").html(res.data.visitCount);
                    $("#buyStatus").html(buyStatus[`${res.data.buyStatus}`]);
                    $("#sharedType").html(
                        res.data.buyRuleId == -1 ? "无条件共享" : "有条件共享"
                    );
                    $("#buyType").html(buyType[`${res.data.buyStatus}`]);
                    $("#brief").html(res.data.brief);
                    $("#detail").html(res.data.detail);
                    const isAuditText = res.data.isAudit === 1 ? '自动审核' : '人工审核'
                    $("#isAudit").html(isAuditText);
                    $("#createBy").html(res.data.createBy);
                    $("#productName").html(res.data.productName);
                    $("#productType").text(productType[res.data.sourceType]);
                    //priceLable(res.data.dataproductPriceList);
                    homologousProduct();
                    if (res.data.isTry === 0) {
                        $("#isTry").text("不可以");
                        $(".applyTry").addClass("disabledNone");
                    } else {
                        $("#isTry").text("可以");
                        $(".applyTry").removeClass("disabledNone");
                    }
                    if (res.data.buyRuleId != -1) {
                        buyRule = res.data.buyRule;
                        if (buyRule) {
                            // 对安全价格进行赋值
                            const security = JSON.parse(buyRule.priceRule).security;
                            console.log('security', security)
                            //计算安全相关价格
                            // const safetyPrice=Number(security.confirm.price)+Number(security.auth.price)+Number(security.encrypt.encode.price)
                            if (security.confirm.select === '1') {
                                safetyPrice+=Number(security.confirm.price)
                            }
                            if (security.auth.select === '1'){
                                safetyPrice+=Number(security.auth.price)
                            }
                            if (security.encrypt.encode.select==='1'){
                                safetyPrice+=Number(security.encrypt.encode.price)
                            }
                            $('.safetyContent #safetyPrice').text(safetyPrice);
                            // 同时对总价初始化
                            $("#totalPrice").text(safetyPrice)
                            buySetData = JSON.parse(buyRule.priceRule).buy;
                            useSetData = JSON.parse(buyRule.priceRule).use;
                            $(".pricingTypeBox").removeClass("disabledNone");
                            $(".useTypeBox").removeClass("disabledNone");
                            console.log('buySetData', buySetData)
                            console.log('useSetData', useSetData)
                            priceLabel(buySetData);
                            useTypeLabel(useSetData);
                        } else {
                            $(".unconditionalBox").removeClass("disabledNone");
                        }
                    } else {
                        $(".unconditionalBox").removeClass("disabledNone");
                    }
                }
            },
        });
    }

    getDataInfo();

    let buyType = {
        访问期限: 4,
        访问次数: 0,
        按记录数访问: 2,
    };
    let useType = {
        使用期限: 4,
        使用次数: 0,
    };
    // 申购产品
    $("#submitShopping").click(function () {
        let buyDataProductForm = {
            customerBillingType: 0,
            customerBillingTypeLocal: 0,
            customerCanUseDay: 0,
            customerCanUseDayLocal: 0,
            customerCanUseNumber: 0,
            customerCanUseNumberLocal: 0,
            customerCanUseRecords: 0,
            customerProductPrice: 0,
            productId: 0,
        };
        customerProductPrice = Number(useTotalPrice) + Number(buyTotalPrice);
        buyDataProductForm.productId = Number(productId);
        buyDataProductForm.customerProductPrice = customerProductPrice;
        // 获取当前选中的购买方式和使用方式
        console.log("购买方式", $("#priceLableBox .price.active").text());
        // 购买方式
        buyDataProductForm.customerBillingType =
            buyType[$("#priceLableBox .price.active").text()] || 0;
        switch (buyDataProductForm.customerBillingType) {
            case 0:
                //TODO 如果是免费试用的，立即申购默认是按照次数购买 买一次
                buyDataProductForm.customerCanUseNumber = useNum || 10000;
                break;
            case 2:
                buyDataProductForm.customerCanUseRecords = useNum;
                break;
            case 4:
                buyDataProductForm.customerCanUseDay = useNum;
                break;
        }
        // console.log('customerBillingType', customerBillingType)
        buyDataProductForm.customerBillingTypeLocal =
            useType[$("#useLableBox .price.active").text()] || 0;
        switch (buyDataProductForm.customerBillingTypeLocal) {
            case 0:
                buyDataProductForm.customerCanUseNumberLocal = buyNum || 10000;
                break;
            case 4:
                buyDataProductForm.customerCanUseDayLocal = buyNum;
                break;
        }

        $.ajax({
            timeout: 30000,
            url: window.Http + "/orderProduct/buyProduct",
            type: "POST",
            headers: {
                Authorization: "Bearer " + sessionStorage.getItem("Token"),
            },
            data: JSON.stringify(buyDataProductForm),
            contentType: "application/json;charset=utf-8",
            success: function (res) {
                if (res.code === 200) {
                    layer.msg(res.msg);
                } else if (res.code === 401) {
                    layer.alert(
                        "未登录，请前往登录界面进行登录",
                        {
                            skin: "layui-layer-lan",
                            closeBtn: 0,
                            anim: 1, //动画类型
                        },
                        function () {
                            window.location.href = "./login.html";
                        }
                    );
                } else {
                    layer.msg(res.msg);
                }
            },
            error: function (err) {
                layer.msg(err.msg);
            },
        });
    });

    $(".decrement").click(function () {
        let productNum = $(".itxt").val();
        if (productNum <= 1) {
            $(".itxt").val(1);
        } else {
            $(".itxt").val(--productNum);
        }
    });
    $(".increment").click(function () {
        let productNum = $(".itxt").val();
        if (productNum < 1) {
            $(".itxt").val(1);
        } else {
            $(".itxt").val(++productNum);
        }
    });

    // 点击加入产品袋
    $(".addShoppingCart").on("click", function () {
        let buyDataProductForm = {
            customerBillingType: 0,
            customerBillingTypeLocal: 0,
            customerCanUseDay: 0,
            customerCanUseDayLocal: 0,
            customerCanUseNumber: 0,
            customerCanUseNumberLocal: 0,
            customerCanUseRecords: 0,
            customerProductPrice: 0,
            productId: 0,
        };
        buyDataProductForm.productId = productId;
        buyDataProductForm.customerProductPrice = customerProductPrice;
        // 获取当前选中的购买方式和使用方式
        console.log("购买方式", $("#priceLableBox .price.active").text());
        // 购买方式
        buyDataProductForm.customerBillingType =
            buyType[$("#priceLableBox .price.active").text()] || 0;
        switch (buyDataProductForm.customerBillingType) {
            case 0:
                //TODO 如果是免费试用的，加入产品袋默认是按照次数购买 买一次
                buyDataProductForm.customerCanUseNumber = buyNum || 10000;
                break;
            case 2:
                buyDataProductForm.customerCanUseRecords = buyNum;
                break;
            case 4:
                buyDataProductForm.customerCanUseDay = buyNum;
                break;
        }
        // console.log('customerBillingType', customerBillingType)
        buyDataProductForm.customerBillingTypeLocal =
            useType[$("#useLableBox .price.active").text()] || 0;
        switch (buyDataProductForm.customerBillingTypeLocal) {
            case 0:
                buyDataProductForm.customerCanUseNumberLocal = buyNum || 10000;
                break;
            case 4:
                buyDataProductForm.customerCanUseDayLocal = buyNum;
                break;
        }
        console.log("buyDataProductForm", buyDataProductForm);
        $.ajax({
            timeout: 30000,
            url: window.Http + "/cart/save",
            type: "POST",
            headers: {
                Authorization: "Bearer " + sessionStorage.getItem("Token"),
            },
            data: JSON.stringify(buyDataProductForm),
            contentType: "application/json;charset=utf-8",
            success: function (res) {
                if (res.code === 200) {
                    layer.msg("成功加入产品袋", {icon: 1});
                } else if (res.code === 401) {
                    layer.alert(
                        "未登录，请前往登录界面进行登录",
                        {
                            skin: "layui-layer-lan",
                            closeBtn: 0,
                            anim: 1, //动画类型
                        },
                        function () {
                            window.location.href = "./login.html";
                        }
                    );
                } else {
                    layer.msg(res.msg);
                }
            },
            error: function (err) {
                layer.msg(err.msg);
            },
        });
    });

    //试用申请
    $(".applyTry").click(function () {
        window.productId = getUrlParam("productId");
        layer.open({
            type: 2,
            title: "试用申请",
            area: ["800px", "480px"],
            content: "./popupPage/applyTryPop.html",
        });
    });

    // 查看数据通道
    $(".viewSource").click(function () {
        window.location.href =
            "./dataStoreDetial.html?sourceId=" + productInfo.sourceId;
    });

    // 查看同源产品
    function homologousProduct() {
        $.ajax({
            timeout: 30000,
            url: window.Http + "/customer/product/list",
            type: "GET",
            headers: {
                Authorization: "Bearer " + sessionStorage.getItem("Token"),
            },
            data: {contentId: productInfo.contentId},
            success: function (res) {
                if (res.code === 200) {
                    console.log(res);
                    let html = "";
                    res.rows.forEach((val) => {
                        if (val.id !== productInfo.id) {
                            let num = Math.ceil(val.score) * 31; //模拟评分
                            let keywords = ''
                            if (val.systemFieldList && val.systemFieldList.length > 0) {
                                val.systemFieldList?.forEach((item, index) => {
                                    keywords += `
                       <span style="border: 1px solid #0ac382;border-radius: 2px;font-size: 12px;color: #0ac382;line-height: 18px;margin-right: 6px;padding: 0 6px;">${item.keyWords.match(/[^,]+/g)[0]}</span>
                   `
                                })
                            } else {
                                keywords = `
                       <span style="border: 1px solid #0ac382;border-radius: 2px;font-size: 12px;color: #0ac382;line-height: 18px;margin-right: 6px;padding: 0 6px;">暂无</span>
                  
                   `
                            }
                            html += `
									<div class="card shadow-sm border-0" data-ID="${val.id}">
										<div class="card-header border-0" >
											<h3 class="my-0 font-weight-normal">${val.productName}</h3>
										</div>
										<div class="card-body">
											<ul class="list-unstyled mt-2 mb-2">
												<li>
													<div style="width:176px;height:99px"><img src="${
                                val.iconUrl
                                    ? val.iconUrl
                                    : "./assets/img/demo/iconURL1.jpg"
                            }" /></div>
												</li>
												<li>
												    ${keywords}
												</li>
												<li>
													<span style="color: #8890a7;font-size:12px;margin-left: -7px;">
												<div class="atar_Show">
												  <p tip="5" style="width:${num}px"></p>
												</div>
												<span></span>
											</span>
												</li>
												<li style="font-weight:400;font-size:12px;line-height:25px;color: #8890a7;">
													<span>访问次数：${val.visitCount}</span>
													<span style="float:right">申购次数：${val.buyCount}</span>
												</li>
												<li style="color: #8890a7;font-size: 14px;overflow: hidden;height: 42px;margin-bottom: 5px;">描述：${
                                val.detail
                            }</li>
											</ul>
										</div>
									</div>
									`;
                        }
                    });
                    $(".homologousProductMenu").append(html);
                }
            },
        });
    }

    // 点击同源产品跳转到详情页面
    $(".homologousProductMenu").delegate(".card", "click", function () {
        let dataId = $(this).attr("data-ID");
        //let Type = $(this).attr("data-TYPE");
        window.location.href = "./productDetail.html?productId=" + dataId;
    });

    //
    /**
     * @description:函数描述 计价方式显示
     * @return 返回值
     * @param buySetData
     */

    function priceLabel(buySetData) {
        for (let key in buySetData) {
            if (key !== "priceWay") {
                //判断规则里面的值是否合法
                if (buySetData[key].minValue < buySetData[key].maxValue) {
                    let newHtml = `<span class="price">${buySetData[key].tip}</span>`;
                    // }else if(buySetData[key].priceway == "add"){
                    // 	addHtml += `<span class="price">${buySetData[key].tip}</span>`
                    // }
                    $("#priceLableBox").append(newHtml);
                }
            }
        }
    }

    /**
     * @description:函数描述 使用方式显示
     * @return 返回值
     * @param useSetData {Object}
     */

    function useTypeLabel(useSetData) {
        for (let key in useSetData) {
            if (key !== "priceWay" && key !== "site") {
                if (useSetData[key].minValue < useSetData[key].maxValue) {
                    let newHtml = `<span class="price">${useSetData[key].tip}</span>`;
                    $("#useLableBox").append(newHtml);
                }
            }
        }
    }

    let buyTotalPrice = 0,
        useTotalPrice = 0;

    /**
     * @description:函数描述 计算申购总价
     * @return 返回值
     * @param data {Object} 具体的规则
     * @param nums {Number} 数量
     */

    function countBuyTotalPrice(data, nums) {
        // console.log('计算价格进度条', data,nums)
        if (data.calcway == "average") {
            console.log("计算价格进度条", nums);
            //平均数公式
            //价格 = 最低价+（（数值-最小值）/（最大值-最小值））*（最高价-最低价）；
            buyTotalPrice =
                data.minPrice +
                ((nums - data.minValue) / (data.maxValue - data.minValue)) *
                (data.maxPrice - data.minPrice);
            buyTotalPrice = buyTotalPrice.toFixed(2);
            console.log("buyTotalPrice", buyTotalPrice);
            let totalPrice = ((buyTotalPrice * 100 + useTotalPrice * 100) / 100)+safetyPrice;
            $("#totalPrice").text(totalPrice);
        } else if (data.calcway == "log") {
            console.log("计算价格进度条", data, nums);
            //对数公式
            //价格 = 最低价+（（Math.log10(数值)-Math.log10(最小值)）/（Math.log10（最大值）-Math.log10(最小值)））*（最高价-最低价）；
            let buyTotalPrice =
                data.minPrice +
                ((Math.log10(nums) - Math.log10(data.minValue)) /
                    (Math.log10(data.maxValue) - Math.log10(data.minValue))) *
                (data.maxPrice - data.minPrice);
            buyTotalPrice = buyTotalPrice.toFixed(2);
            let totalPrice = ((buyTotalPrice * 100 + useTotalPrice * 100) / 100)+safetyPrice;
            $("#totalPrice").text(totalPrice);
        }
    }

    /**
     * @description:函数描述 计算使用总价
     * @return 返回值
     * @param data
     * @param nums
     */

    function countUseTotalPrice(data, nums) {
        console.log("useTotalPrice", useTotalPrice);
        if (data.calcway == "average") {
            //平均数公式
            //价格 = 最低价+（（数值-最小值）/（最大值-最小值））*（最高价-最低价）；
            useTotalPrice =
                data.minPrice +
                ((nums - data.minValue) / (data.maxValue - data.minValue)) *
                (data.maxPrice - data.minPrice);
            useTotalPrice = useTotalPrice.toFixed(2);
            let totalPrice = ((buyTotalPrice * 100 + useTotalPrice * 100) / 100)+safetyPrice;
            $("#totalPrice").text(totalPrice);
        } else if (data.calcway == "log") {
            //对数公式
            //价格 = 最低价+（（Math.log10(数值)-Math.log10(最小值)）/（Math.log10（最大值）-Math.log10(最小值)））*（最高价-最低价）；
            let useTotalPrice =
                data.minPrice +
                ((Math.log10(nums) - Math.log10(data.minValue)) /
                    (Math.log10(data.maxValue) - Math.log10(data.minValue))) *
                (data.maxPrice - data.minPrice);
            useTotalPrice = useTotalPrice.toFixed(2);
            let totalPrice = ((buyTotalPrice * 100 + useTotalPrice * 100) / 100)+safetyPrice;
            customerProductPrice = totalPrice;
            $("#totalPrice").text(totalPrice);
        }
    }

    //选择价格方式
    $("#priceLableBox").delegate(".price", "click", function (e) {
        $(this).addClass("active").siblings(".price").removeClass("active");
        let tipVal = $(this).text();
        if (tipVal === "访问期限") {
            $("#buyCalculateUnit").text("(天数)");
        } else if (tipVal === "按记录数访问") {
            $("#buyCalculateUnit").text("（KB)");
        } else {
            $("#buyCalculateUnit").text("(次数)");
        }

        for (let key in buySetData) {
            if (buySetData.priceWay === "new" && tipVal == buySetData[key].tip) {
                //数量范围
                layui.use("slider", function () {
                    var $ = layui.$,
                        slider = layui.slider;
                    slider.render({
                        elem: "#buySlideNumber",
                        min: buySetData[key].minValue, //最小值
                        max: buySetData[key].maxValue, //最大值
                        change: function (values) {
                            buyNum = values;
                            countBuyTotalPrice(buySetData[key], values);
                        },
                    });
                });
                console.log("buySetData[key].minPrice", buySetData[key].minPrice);
                //价格范围
                $("#buyMinprice").text(buySetData[key].minPrice);
                $("#buyMaxprice").text(buySetData[key].maxPrice);
            }
        }
    });
    //选择使用方式
    $("#useLableBox").delegate(".price", "click", function (e) {
        $(this).addClass("active").siblings(".price").removeClass("active");
        let tipVal = $(this).text();
        if (tipVal == "使用期限") {
            $("#useCalculateUnit").text("(天数)");
        } else {
            $("#useCalculateUnit").text("(次数)");
        }
        let currentData;
        for (let key in useSetData) {
            if (useSetData.priceWay === "add" && tipVal == useSetData[key].tip) {
                currentData = useSetData[key];
            }
        }
        //数量范围
        if (currentData) {
            layui.use("slider", function () {
                var $ = layui.$,
                    slider = layui.slider;
                slider.render({
                    elem: "#useSlideNumber",
                    min: currentData.minValue, //最小值
                    max: currentData.maxValue, //最大值
                    change: function (values) {
                        useNum = values;
                        countUseTotalPrice(currentData, values);
                    },
                });
            });
            //价格范围
            $("#useMinprice").text(currentData.minPrice);
            $("#useMaxprice").text(currentData.maxPrice);
        } else {
            $("#useSlideNumber").empty();
            //价格范围
            $("#useMinprice").text(0);
            $("#useMaxprice").text(0);
        }
    });

    //评价
    layui.use(["laypage", "layer"], function () {
        var laypage = layui.laypage,
            layer = layui.layer;
        laypage.render({
            elem: "evaluatePage",
            count: 100,
            layout: ["count", "prev", "page", "next"],
            jump: function (obj) {
                console.log(obj);
            },
        });
    });
});
